<?php
/**
 * Created by PhpStorm.
 * User: lixiaohui
 * Date: 2015/9/22
 * Time: 17:50
 */

namespace Home\Controller;


use Think\Controller;
use Think\Exception;
use Think\Log;

/**
 * Class PayController
 * @package Home\Controller 水费缴纳controller
 */
class PayController extends Controller
{
    //GetUserInfo查询类型
    const USER_INFO_QUERY_TYPE_USER_ID = 1;
    const USER_INFO_QUERY_TYPE_IDENTITY = 2;

    //用户类型
    const USER_TYPE_PAY = 1;
    const USER_TYPE_PRESAVE = 2;

    //首页
    public function index()
    {
        //取出所有绑定的账号
        $relevanceModel = M('member_relevance')->where("openid='%s'", getOpenId())->field('id,userid')->select();
        $this->assign("relevanceModel", $relevanceModel);
        $this->assign("bottomMenu", getBottomMenu());
        $this->display();
    }

    /**水费清单列表详情
     * 按欠费账单金额进行缴费，操作流程如下：
     * 1、查询用户信息，必须是非预存用户才能使用该功能
     * 2、查询用户欠费账单，显示欠费总金额
     * 3、确认缴费，此时要求后台生成缴费订单
     * 4、调用微信进行支付
     * 5、后台接收到微信支付成功消息，进行账单缴费
     * @throws \Think\Exception
     */
    public function detail()
    {
        $userid = I('userid');
        $args = array(
            "userid" => $userid,
        );
        //判断用户类型(缴费用户,预存用户)GetUserInfo
        $typeArgs = array(
            "queryType" => self::USER_INFO_QUERY_TYPE_USER_ID,
            "queryKey" => $userid
        );
        $typePostString = getPostString('GetUserInfo', $typeArgs);
        Log::write($typePostString);

        $typeRetStr = post(C('INTERFACE_BASE_URL'), $typePostString);
        Log::write($typeRetStr);

        $typeRetObj = json_decode($typeRetStr, true);
        //没找到用户
        if (intval($typeRetObj['retcode']) != 0) {
            $this->ajaxReturn(array("retcode" => "-1", "errmsg" => "用户 '$userid' 不存在"));
        }
        //找到的用户为预存用户
        if (intval($typeRetObj['retcode']) == self::USER_TYPE_PRESAVE) {
            $this->ajaxReturn(array("retcode" => "-1", "errmsg" => $typeRetObj['errmsg']));
        }
        //找到的用户为缴费用户
        //请求用户水费清单
        $postString = getPostString('GetUserBill', $args);
        Log::write('postString=' . $postString);
        $retStr = post(C('INTERFACE_BASE_URL'), $postString);
        Log::write('retString=' . $retStr);

        $retObj = json_decode($retStr, true);

        $totalFee = 0.0;//单位分
        //计算总额
        foreach ($retObj['data']['list'] as $key => $value) {//未支付判断条件:paytime=''
            $totalFee += floatval($value['billamount']);
        }
        $retObj['totalFeeInFen'] = abs(intval($totalFee));//分钱,整数，微信下单
        $totalFee = number_format($totalFee / 100, 2);
        $retObj['totalFeeInYuan'] = abs($totalFee);//元钱，两位小数
        $retObj['userid'] = $userid;
        //dump($retObj);
        $this->assign("json", $retObj);
        $this->display();
    }

    /**
     * 微信下单
     */
    public function placeOrderInWeiXin()
    {
        $totalFeeInFen = I('totalFee');
		//$totalFeeInFen = (int)((float)$totalFeeInFen / 1000);
        //$totalFeeInFen = 1;
        $userid = I('userid');

        if(intval($totalFeeInFen) < 0){
            $this -> ajaxReturn(array(
                "status"=>"fail",
                "msg"=>"支付金额应大于0"
            ));
        }
        $notifyUrl = C('NOTIFY_URL');//微信回调url
        $outTradeNo = $userid . date("YmdHis");

        $tools = getTools();
        $openId = getOpenId();
        //微信统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("缴纳水费");
        $input->SetAttach("缴纳水费");
        $input->SetOut_trade_no($outTradeNo);
        $input->SetTotal_fee(1);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("缴纳水费");
        $input->SetNotify_url($notifyUrl);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $chargeDate = date('Y-m-d H:i:s');
        //返回页面的订单信息
        $orderInfo = array(
            "userId"=>$userid,
            "outTradeNo"=>$outTradeNo,  //微信商户订单号
            "userAtr"=>1,//用户缴费属性 1-缴费用户,2-预存用户
            "tradeNo"=>$outTradeNo,//交易流水号
            "way"=>4,   //1-营业厅；2-自助终端；3-银联代扣；4-第三方代充
            "payType"=>3,   //1－现金；2－银联；3－微信；4－支付宝
            "payTime"=>$chargeDate,  //格式：yyyy-MM-dd hh:mm:ss
            "amount"=>$totalFeeInFen //支付总额，单位分
        );
        //生成订单保存订单表
        $saveOrder = array(
            "oriderID"=>$outTradeNo,    //订单号，此处保持微信商户订单号一致
            "ChargeDate"=>$chargeDate,  //日期
            "UserId"=>$userid, //水费账号
            "Amount"=>intval($totalFeeInFen),//充值金额
            "openID"=>getOpenId(),//微信openid
            "BusinessType"=>"1",//业务类型(1缴费 2预存)
            "TopupStatus"=>"1",//充值状态(0已支付，1未支付)
            "TopupType"=>"1",//充值类型(1微信充值)
            "refno"=>$outTradeNo //系统充值单号
        );
        Log::write(json_encode($saveOrder));
        $saveResult = M('order_info') -> add($saveOrder);
        if($saveResult < 0){//保存失败
            $this->ajaxReturn(array(
                "status"=>"fail",
                "msg"=>"后台提交订单失败!"
            ));
        }
        //下单成功
        $this->ajaxReturn(array(
            "status"=>"success",
            "jsApiParameters"=>json_decode($jsApiParameters,true),
            "orderInfo"=>$orderInfo,
            "msg"=>"下单成功!"
            ));
    }

    //微信支付后调用该方法进行账单缴费
    public function Recharge(){
        $args = array(
            "userid"=>I('userId'),
            "useratr"=>I('userAtr'),
            "tradeno"=>I('tradeNo'),
            "way"=>I('way'),
            "paytype"=>I('payType'),
            "paytime"=>I('payTime'),
            "amount"=>intval(I('amount'))
        );
        Log::write('args='.json_encode($args));
        $postString = getPostString('Recharge',$args);
        Log::write('recharge'.$postString);
        $retStr = post(C('INTERFACE_BASE_URL'),$postString);
        Log::write('retStr='.$retStr);
        $this->ajaxReturn(array(
            "status"=>"success",
            "rechargeResult"=>json_decode($retStr,true)
        ));

    }
    //支付成功页面
    public function success(){
        $param = I('param');
        Log::write("param=$param");
        $htmlSpecialChars = htmlspecialchars_decode($param);
        Log::write("htmlSpecialChars=$htmlSpecialChars");
        $param = json_decode($htmlSpecialChars,true);
        $this -> assign('rechargeResult',$param);
        $this -> display();
    }
}